import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLineEdit, QPushButton,
                             QVBoxLayout, QHBoxLayout, QWidget, QLabel,
                             QScrollArea, QFrame)
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QFont, QPalette, QColor


# 处理AI响应的工作线程
class AIChatWorker(QThread):
    response_ready = pyqtSignal(str)

    def __init__(self, user_message):
        super().__init__()
        self.user_message = user_message

    def run(self):
        # 模拟AI思考时间
        self.msleep(800)

        # 检测天气相关问题
        weather_keywords = ["天气", "气温", "下雨", "晴天", "多云", "刮风"]
        if any(keyword in self.user_message for keyword in weather_keywords):
            response = "今日的天气，宛如一幅未完成的画作里那突兀的钝角，带着几分朦胧与混沌，在天地间勾勒出别样的景致"
        else:
            response = "我是智能客服，请问有什么可以帮助您的吗？"

        self.response_ready.emit(response)


# 主窗口类
class AIChatbotWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # 窗口基本设置
        self.setWindowTitle("屎王的天气智能客服")
        self.setGeometry(100, 100, 600, 700)
        self.setMinimumSize(400, 500)

        # 设置中文字体
        font = QFont()
        font.setFamily("SimHei")
        font.setPointSize(11)
        self.setFont(font)

        # 主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(10)

        # 聊天历史区域
        self.chat_scroll_area = QScrollArea()
        self.chat_scroll_area.setWidgetResizable(True)
        self.chat_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.chat_scroll_area.setStyleSheet("QScrollArea { border: none; }")

        self.chat_container = QWidget()
        self.chat_container.setStyleSheet("background-color: #f5f5f5; border-radius: 8px;")
        self.chat_layout = QVBoxLayout(self.chat_container)
        self.chat_layout.setAlignment(Qt.AlignTop)
        self.chat_layout.setSpacing(15)
        self.chat_layout.setContentsMargins(15, 15, 15, 15)

        self.chat_scroll_area.setWidget(self.chat_container)
        main_layout.addWidget(self.chat_scroll_area)

        # 输入区域
        input_widget = QWidget()
        input_layout = QHBoxLayout(input_widget)
        input_layout.setContentsMargins(0, 5, 0, 0)
        input_layout.setSpacing(10)

        self.message_input = QLineEdit()
        self.message_input.setPlaceholderText("请输入您的问题...")
        self.message_input.setStyleSheet("""
            QLineEdit {
                padding: 10px;
                border: 1px solid #ddd;
                border-radius: 20px;
                background-color: white;
            }
        """)
        self.message_input.returnPressed.connect(self.send_message)
        input_layout.addWidget(self.message_input, 8)

        self.send_button = QPushButton("发送")
        self.send_button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                padding: 10px 20px;
                border: none;
                border-radius: 20px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:pressed {
                background-color: #3d8b40;
            }
        """)
        self.send_button.clicked.connect(self.send_message)
        input_layout.addWidget(self.send_button, 2)

        main_layout.addWidget(input_widget)

        # 设置布局比例
        main_layout.setStretch(0, 8)  # 聊天区域占80%
        main_layout.setStretch(1, 2)  # 输入区域占20%

        # 添加欢迎消息
        self.add_message("您好", is_user=False)

    def add_message(self, text, is_user):
        """添加消息到聊天区域"""
        # 创建消息容器
        msg_container = QWidget()
        msg_container.setStyleSheet("background-color: transparent;")
        layout = QHBoxLayout(msg_container)
        layout.setContentsMargins(0, 0, 0, 0)

        # 设置对齐方式
        if is_user:
            layout.setAlignment(Qt.AlignRight)
        else:
            layout.setAlignment(Qt.AlignLeft)

        # 创建消息气泡
        bubble = QFrame()
        max_width = int(self.width() * 0.65)  # 消息最大宽度为窗口的65%
        bubble.setMaximumWidth(max_width)
        bubble.setMinimumWidth(60)

        # 设置气泡样式
        if is_user:
            # 用户消息 - 右侧，绿色背景
            bubble.setStyleSheet("""
                QFrame {
                    background-color: #95ec69;
                    border-radius: 15px;
                    padding: 10px 15px;
                }
            """)
        else:
            # AI消息 - 左侧，白色背景
            bubble.setStyleSheet("""
                QFrame {
                    background-color: white;
                    border: 1px solid #e0e0e0;
                    border-radius: 15px;
                    padding: 10px 15px;
                }
            """)

        # 消息文本
        msg_label = QLabel(text)
        msg_label.setWordWrap(True)
        msg_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        msg_label.setStyleSheet("color: #333;")

        # 添加到气泡
        bubble_layout = QHBoxLayout(bubble)
        bubble_layout.setContentsMargins(0, 0, 0, 0)
        bubble_layout.addWidget(msg_label)

        # 添加到容器
        layout.addWidget(bubble)

        # 添加到聊天布局
        self.chat_layout.addWidget(msg_container)

        # 滚动到底部
        self.chat_scroll_area.verticalScrollBar().setValue(
            self.chat_scroll_area.verticalScrollBar().maximum()
        )

    def send_message(self):
        """发送用户消息并获取AI响应"""
        text = self.message_input.text().strip()
        if not text:
            return

        # 添加用户消息到聊天记录
        self.add_message(text, is_user=True)
        self.message_input.clear()

        # 禁用发送按钮防止重复发送
        self.send_button.setEnabled(False)
        self.message_input.setEnabled(False)

        # 启动AI处理线程
        self.worker = AIChatWorker(text)
        self.worker.response_ready.connect(self.on_ai_response)
        self.worker.response_ready.connect(lambda: self.send_button.setEnabled(True))
        self.worker.response_ready.connect(lambda: self.message_input.setEnabled(True))
        self.worker.start()

    def on_ai_response(self, response):
        """处理AI的响应"""
        self.add_message(response, is_user=False)

    def resizeEvent(self, event):
        """窗口大小改变时调整消息气泡宽度"""
        super().resizeEvent(event)
        max_width = int(self.width() * 0.65)

        # 调整所有消息气泡宽度
        for i in range(self.chat_layout.count()):
            container = self.chat_layout.itemAt(i).widget()
            if container:
                layout = container.layout()
                if layout and layout.count() > 0:
                    bubble = layout.itemAt(0).widget()
                    if bubble:
                        bubble.setMaximumWidth(max_width)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 设置全局样式
    app.setStyle("Fusion")

    # 设置全局背景色
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(240, 240, 240))
    app.setPalette(palette)

    window = AIChatbotWindow()
    window.show()
    sys.exit(app.exec_())
